<?php

namespace app\api\controller\v1\store;

use app\model\order\StoreOrder;
use app\model\user\User;
use app\model\user\UserBill;
use app\Request;
use app\services\order\StoreOrderRefundServices;
use app\services\product\product\StoreCategoryServices;
use app\services\user\UserServices;
use app\services\notice\UserNoticeServices;
use think\facade\Db;

/**
 * Class CategoryController
 * @package app\api\controller\v1\store
 */
class CategoryController
{
    protected $services;

    public function __construct(StoreCategoryServices $services) {
        $this->services = $services;
    }

    /**
     * 获取分类列表
     * @return mixed
     */
    public function category() {
        $category = $this->services->getCategory();
        return app('json')->success($category);
    }

    /**
     * 获取分类列表
     * @return mixed
     */
    public function get_category() {
        $category = $this->services->getCategory();
        return app('json')->success($category);
    }

    /**
     * get_product
     */
    public function get_product(Request $request) {
        $cate_id = $request->post('cate_id');
        $type = $request->post('pink_type', 4);
        $is_experience = $request->post('is_experience', 2);
        $ey_where_str = '';
        if ($cate_id) {
            $where['cate_id'] = $cate_id;
            $ey_where_str .= ' and cate_id=' . $cate_id;
        }

        if ($type) {
            $ey_where_str .= ' and pink_type=' . $type;
        }
        if ($is_experience) {
            $ey_where_str .= ' and is_experience=' . $is_experience;
        }
        $list = Db::query('select * from eb_store_product where is_show = 1 and is_del = 0 and stock > 0 and pink_type in (4,5,6,7) and product_type = 1 ' . $ey_where_str . ' order by sort desc limit 0,50');

        //$ey_where_str .= ' and pink_type ='.$where['pink_type'];

        // $list = Db::table('eb_store_product')->where($where)->select()->toArray();
        // $list = Db::query('select * from eb_store_product where is_show = 1 and is_del = 0 and product_type = 1 and ((pt_start_time =0 and pt_end_time =0) or (pt_start_time < '.time().' and pt_end_time > '.time().' )) '.$ey_where_str.' order by sort desc limit 0,10');
        //return Db::getLastSql();
        return app('json')->success($list);
    }
    /**
     * get_product2
     * 获取积分兑换产品
     */
    public function get_product2(Request $request) {
        $cate_id = $request->post('cate_id');

        $ey_where_str = '';
        if ($cate_id) {
            $ey_where_str .= " and (cate_id='{$cate_id}' or cate_id like '%{$cate_id},%' or cate_id like '%,{$cate_id}%') ";
        }

        // $list = Db::table('eb_store_product')->where($where)->select()->toArray();
        $list = Db::query('select * from eb_store_product where is_show = 1 and is_del = 0 and product_type = 2 ' . $ey_where_str . ' order by sort desc  limit 0,50');
        //return Db::getLastSql();
        return app('json')->success($list);
    }

    /**
     * 获取拼团设置
     */
    public function get_pingtuan_setting() {
        $setting = Db::table('eb_combination_setting')->select()->toArray();
        $config = array();
        foreach ($setting as $key => $value) {
            $config[$value['name']] = $value['value'];
        }
        $return['status'] = 200;
        $return['config'] = $config;
        return json($return);
    }

    /**
     * 设置银行卡
     */
    public function set_card(Request $request) {
        $card_name = $request->post('card_name', '');
        $card_number = $request->post('card_number', '');
        $card_bank = $request->post('card_bank');
        $uid = $request->uid();
        Db::table('eb_user')->where('uid', $uid)->update([
            'card_name' => $card_name,
            'card_number' => $card_number,
            'card_bank' => $card_bank
        ]);
        return app('json')->success('设置成功');
    }

    /**
     * 申请提货
     */
    public function apply_th(Request $request) {
        //要扣除运费，再设置
        $uid = $request->uid();
        $user = User::find($uid);
        $now_money = $user->now_money;

        $order_id = $request->post('id');
        $order = StoreOrder::find($order_id);
        $postage = $order->total_postage;

        if (floatval($now_money) < floatval($postage)) {
            return app('json')->fail('余额不足');
        } else {
            $remind = bcsub($now_money, $postage, 2);
            $user->now_money = $remind;
            $order->th_status = 1;
            //保存 插入
            $user->save();
            $order->save();
            //插入账单信息
            $bill = new UserBill();
            $bill->uid = $uid;
            $bill->link_id = $order_id;
            $bill->pm = 0;
            $bill->title = '支付运费';
            $bill->category = 'now_money';
            $bill->type = 'pay_money';
            $bill->number = $postage;
            $bill->balance = $remind;
            $bill->add_time = time();
            $bill->mark = '';
            $bill->status = 1;
            $bill->take = 0;
            $bill->save();
            return app('json')->success('提货成功，请等待后台审核');
        }

    }

    /**
     * 兑换成积分
     */
    public function apply_dh(Request $request) {
        //订单金额兑换成积分
        $uid = $request->uid();
        $user = User::find($uid);

        $order_id = $request->post('id');
        $order = StoreOrder::where('uid', $uid)->find($order_id);

        //实际金额
        $pay_price = $order->pay_price;

        //实际金额转移到积分然后修改订单状态
        $user->points = bcadd($user->points, $order->pay_price, 2);

        $order->th_status = 4;

        $user->save();

        $order->save();

        //插入账单信息
        $bill = new UserBill();
        $bill->uid = $uid;
        $bill->link_id = $order_id;
        $bill->pm = 1;
        $bill->title = '积分兑换';
        $bill->category = 'points';
        $bill->type = 'exchange_points';
        $bill->number = $order->pay_price;
        $bill->balance = $user->points;
        $bill->add_time = time();
        $bill->mark = '';
        $bill->status = 1;
        $bill->take = 0;
        $bill->save();

        return app('json')->success('兑换成功');
    }

    /**
     * 获取页面购买时间
     */
    public function get_can_buy() {
        //获取时间段
        $start_time = get_pingtuan_config('pt_start');
        $start_time = strtotime($start_time);
        $end_time = get_pingtuan_config('pt_end');
        $end_time = strtotime($end_time);
        $now = time();
        if ($now > $start_time && $now < $end_time) {
            $return['can_buy'] = 1;
        } else {
            $return['can_buy'] = 0;
        }
        $return['status'] = 200;
        return json($return);
    }

    /**
     * 申请退款
     */
    public function apply_tk(Request $request, StoreOrderRefundServices $services) {
        $id = $request->post('id');

        $order = Db::table('eb_store_order')
            ->where('id', $id)
            ->where('refund_status', 0)
            ->find();
        if ($order) {
            $update_result = Db::table('eb_store_order')
                ->where('id', $id)
                ->where('refund_status', 0)
                ->update([
                    'refund_status' => 2
                ]);
        } else {
            return app('json')->success('退款失败，没有符合条件的订单');
        }


        //生成退款单，然后直接退款
        //$services = new StoreOrderRefundServices();
        $services->refundOrderForm((int)$id);


        //改 用户前台提交退款，不用后台确认，提交退款时，直接订单发送到这里，做退款操作

        $tk_price = $order['total_price'];
        $pink_type = $order['pink_type'];
        $fanlibili = get_pingtuan_config('pink' . $pink_type . '_rebate');
        //退款金额等于 商品金额修改后不加运费金额
        $tk_price = $tk_price * (1 + $fanlibili / 100);

        $data['refund_price'] = $tk_price;
        $data['type'] = 1;
        if (!$id) {
            return $this->fail('Data does not exist!');
        }
        $order = $services->get($id);
        if (!$order) {
            return $this->fail('Data does not exist!');
        }
        if ($order['pay_price'] == $order['refund_price']) {
            return $this->fail('已退完支付金额!不能再退款了');
        }
        if (!$data['refund_price']) {
            return $this->fail('请输入退款金额');
        }
        $refund_price = $data['refund_price'];
        $data['refund_price'] = bcadd($data['refund_price'], $order['refund_price'], 2);
        $bj = bccomp((string)$order['pay_price'], (string)$data['refund_price'], 2);
//        if ($bj < 0) {
//            return $this->fail('退款金额大于支付金额，请修改退款金额');
//        }
        if ($data['type'] == 1) {
            $data['refund_status'] = 2;
        } else if ($data['type'] == 2) {
            $data['refund_status'] = 0;
        }
        $type = $data['type'];
        unset($data['type']);
        $refund_data['pay_price'] = $order['pay_price'];
        $refund_data['refund_price'] = $refund_price;
        if ($order['refund_price'] > 0) {
            $refund_data['refund_id'] = $order['order_id'] . rand(100, 999);
        }

        //退款处理
        $services->payOrderRefund($type, $order, $refund_data);

        //回退库存
        $services->regressionStock($order);

        //修改订单退款状态
        if ($this->services->update($id, $data)) {
            $services->storeProductOrderRefundY($data, $order, $refund_price);
            //return $this->success('退款成功');
        } else {
            $services->storeProductOrderRefundYFasle((int)$id, $refund_price);
            //return $this->fail('退款失败');
        }

        if ($update_result) {
            return app('json')->success('退款成功，请进入余额查看');
        }
    }
}
